<template>
  <div>
    <Row>
      <Col span="24">
      <Card>
        <p slot="title">
          <Icon type="ios-list"></Icon>
          角色实例列表
        </p>
        <Row>
          <Input v-model="searchModel.userRoleName" placeholder="请输入角色实例名称..." style="width: 300px"></Input>
          <Button type="primary" shape="circle" @click="searchUserRole" :loading="searchLoading" icon="ios-search">
            <span>搜索角色实例</span>
          </Button>
        </Row>

        <Row type="flex" justify="center" align="middle">
          <Table border :columns="columnHeader" :data="userRoleList"></Table>
        </Row>
        <Row type="flex" justify="center" align="middle">
          <Page :total="total" :current="current" :page-size="pageSize" :show-tota="showTotal" @on-change="onChange"
                show-elevator></Page>
        </Row>


      </Card>
      </Col>
    </Row>
    <Modal v-model="showPermissionMenu" title="授权菜单" :mask-closable="false" @on-ok="saveThePermissionToRole">
      <Tree :data="permissionMenuList" show-checkbox multiple ref="authTree"></Tree>
    </Modal>

    <Modal v-model="showPermissionData" title="数据权限授权" :mask-closable="false" @on-ok="saveThePermissionDataToUserRole">

      <Form label-position="left" :label-width="100">
        <FormItem label="数据权限类型">
          <Select v-model="dataPermissionModel" @on-change="onChangePermission" style="width:300px">
            <Option v-for="item in permissionDataModel" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>

        <FormItem label="选择机构" v-if="showOrganization">
          <Select v-model="organizationIds" filterable multiple>
            <Option v-for="organization in organizationList" :value="organization.organizationId"
                    :key="organization.organizationId">{{ organization.showOrganizationName }}
            </Option>
          </Select>
        </FormItem>

      </Form>


    </Modal>

  </div>
</template>
<script>
  import util from '@/lib/util.js';

  export default {
    data() {
      return {
        searchLoading: false,
        selectedUserRoleId: null,
        dataPermissionModel: null,
        permissionMenuList: [],
        organizationList: [],
        organizationIds: [],
        showPermissionMenu: false,
        showPermissionData: false,
        showOrganization: false,
        permissionDataModel: [
          {
            value: '1',
            label: '系统全部数据'
          }, {
            value: '2',
            label: '所属机构及本机构下属所有机构数据'
          }, {
            value: '3',
            label: '只所属构数据'
          }, {
            value: '4',
            label: '指定机构+指定机构下属机构数据'
          }, {
            value: '5',
            label: '指定机构数据'
          }, {
            value: '6',
            label: '自己负责的数据'
          }
        ],
        searchModel: {
          userRoleName: '',
          pageSize: 10,
          pageNum: 1
        },
        columnHeader: [
          {
            title: '角色实例名称',
            key: 'userRoleName',
            width: 200,
            fixed: 'left'
          },
          {
            title: '用户名称',
            key: 'userName',
            width: 100,
            fixed: 'left'
          },
          {
            title: '性别',
            key: 'genderName',
            width: 80,
            fixed: 'left'
          },
          {
            title: '机构名称',
            key: 'organizationName',
            width: 200,
            fixed: 'left'
          },
          {
            title: '角色实例状态',
            key: 'state',
            width: 120,
            fixed: 'left',
            render: (h, params) => {
              return h('div', [
                h('i-switch', {
                  props: {
                    value: params.row.state == 1,
                    size: 'large'
                  },
                  on: {
                    'on-change': (value) => {
                      this.changeUserRoleState(value, params.row)
                    }
                  }
                }, [
                  h('span', {
                    slot: 'open'
                  }, '正常'),
                  h('span', {
                    slot: 'close',
                  }, '冻结')
                ])
              ]);
            }
          },

          {
            title: '创建日期',
            key: 'createDate',
            width: 200,
            fixed: 'left',
            render: function (h, params) {
              return h('div',
                util.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd hh:mm'))
            }
          },
          {
            title: '操作',
            key: 'action',
            width: 240,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.permissionMenu(params.row)
                    }
                  },
                  directives: [
                    {
                      name: 'hasPermissionButton',
                      value: '/admin/userRole/saveThePermissionToRoleButton'
                    }
                  ]
                }, '授权菜单&按钮'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.permissionData(params.row)
                    }
                  },
                  directives: [
                    {
                      name: 'hasPermissionButton',
                      value: '/admin/userRole/saveThePermissionToRoleButton'
                    }
                  ]
                }, '数据权限')
              ]);
            }
          }
        ],
        userRoleList: [],
        total: null,
        current: null,
        pageSize: null,
        showTotal: true

      }
    },
    methods: {

      getUserRolePage() {
        this.userRoleList = [];
        let that = this;
        util.post("/admin/permission/getUserRolePage", this.searchModel, function (res) {
          let userRoleList = res.list;
          userRoleList.forEach(item => {
            that.userRoleList.push(item);
          });
          that.total = res.total;
          that.current = res.pageNum;
          that.pageSize = res.pageSize;
        })
      },

      searchUserRole() {
        this.getUserRolePage();
      },
      onChange(pageNum) {
        this.searchModel.pageNum = pageNum;
      },
      permissionMenu(row) {
        this.permissionMenuList = [];
        let that = this;
        this.selectedUserRoleId = row.userRoleId;
        util.post('/admin/permission/getPermissionList', {
          userRoleId: row.userRoleId
        }, function (data) {
          data.forEach(item => {
            that.permissionMenuList.push(item);
          });
          that.showPermissionMenu = true;
        });

      },
      initOrgList() {
        let that = this;
        that.organizationList = [];
        this.$http.post('/api/admin/organization/all', {}).then(res => {
          let initOrgList = res.data;
          initOrgList.forEach(item => {
            that.organizationList.push(item);
          });

        }).catch(err => {

        });
      },

      /**
       * 数据权限配置
       */
      permissionData(row) {
        this.organizationIds = [];
        this.dataPermissionModel = null;
        let that = this;
        this.selectedUserRoleId = row.userRoleId;
        util.post('/admin/permission/getThePermissionDataByUserRole', {
          userRoleId: row.userRoleId
        }, function (res) {
          that.showPermissionData = true;
          if(res == undefined){
            return;
          }

          console.log(res);
          that.organizationIds = [];
          that.dataPermissionModel = res.dataPermissionModel+"";
          if(res.dataPermissionModel == 4 || res.dataPermissionModel == 5){
            that.showOrganization = true;
            //解析机构
            let arrOrg  = res.orgIds.split(',');
            arrOrg.forEach(item =>{
              if(item){

                that.organizationIds.push(parseInt(item));
              }
            })


          }else{
            that.showOrganization = false;
          }
        }, false)

      },

      saveThePermissionDataToUserRole() {

        let permissionOrgIds = '';
        this.organizationIds.forEach(item => {
          permissionOrgIds += item + ',';
        });

        let that = this;
        util.post('/admin/permission/saveThePermissionDataToUserRole', {
          userRoleId: that.selectedUserRoleId,
          dataPermissionModel: that.dataPermissionModel,
          orgIds: permissionOrgIds
        }, function (data) {

        }, true)
      },

      changeUserRoleState(state, userRole) {
        util.post("/admin/permission/updateUserRole", {
          userRoleId: userRole.userRoleId,
          state: state ? 1 : 0
        }, function (data) {

        }, true);
      },

      onChangePermission(item) {
        this.organizationIds = [];
        if (item == 4 || item == 5) {
          this.showOrganization = true;
        } else {
          this.showOrganization = false;
        }
      },


      saveThePermissionToRole() {


        let that = this;
        let data = that.$refs.authTree.getCheckedNodes();
        let menuIds = '';
        let parentIds = '';
        data.forEach(item => {
          if (item.checked && !item.disabled) {
            if (item.parentMenuId) {
              parentIds += item.parentMenuId + ',';
            }
            menuIds += item.menuId + ',';
          }
        });
        util.post('/admin/permission/saveThePermissionToRole', {
          userRoleId: that.selectedUserRoleId,
          menuIds: menuIds + parentIds
        }, function (data) {

        }, true)


      },
    },

    mounted() {
      this.getUserRolePage();
      this.initOrgList();
    }
  }
</script>
